<!--  -->
<template>
  <div id="AuthorizedLogin">
    <div class="speace"></div>
    <div class="shopBox">
      <div class="img">
        <img :src="default_head_img" alt="" />
      </div>
      <div class="shopName">{{shop_name}}</div>
    </div>
    <div class="txt" style="">申请获取以下权限</div>
    <div class="txt" style="font-size: 1.19rem;">获得你的公开信息（昵称、头像等）</div>
    <div class="btnBox">
      <van-button style="margin-top: 11.72rem; background: var(--themeLoadingColor); color: #fff;" round @click="beforeToLogin">授权登录</van-button>
      <van-button style="margin-top: 1.56rem; border: 1px solid var(--themeLoadingColor); color: var(--themeLoadingColor);" round @click="toMember">暂不登录</van-button>
      <div class="agreement" v-if="platform_protocol || register_protocol">
        <van-checkbox v-model="checkedSelect" :checked-color="theme_color"></van-checkbox>
        <div class="agreement_txt">
          我已阅读并同意<span class="redTxt" v-if="register_protocol" @click="tapShowAgreement('register')">《{{ register_protocol.title }}》</span
          ><span class="redTxt" v-if="platform_protocol" @click="tapShowAgreement('platform')">《{{ platform_protocol.title }}》</span>
        </div>
      </div>
    </div>
    <van-popup v-model="tipsShow" style="border-radius: 0.656rem;" :close-on-click-overlay="false">
      <div class="contenBox">
        <div class="contenTitle">
          <div class="title">请阅读并同意</div>
          <div class="agree" v-if="register_protocol || platform_protocol">
            <span @click="tapShowAgreement('register')" v-show="register_protocol.title">《{{ register_protocol.title }}》</span><span @click="tapShowAgreement('platform')" v-show="platform_protocol.title">《{{ platform_protocol.title }}》</span>
          </div>
        </div>
        <div class="buttonBox">
          <div class="btn_c" @click="tipsShow = false">不同意</div>
          <div class="btn" @click="comfirm">同意</div>
        </div>
      </div>
    </van-popup>
    <!-- 协议弹窗-->
    <van-popup v-model="openAgreement" style="border-radius: 0.656rem;" :close-on-click-overlay="false">
      <div class="city-info">
        <van-nav-bar :title="popoverProtocolContent.title" fixed />
        <div style="height: 2.5rem; clear: both;"></div>
        <div id="a_content" v-html="popoverProtocolContent.content"></div>
        <div class="openBtn" @click="openAgreement = false">
          确定
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import base64_decode from "@/utils/base64_decode";
const sdk = window.douyin_open;
export default {
  data() {
    return {
      default_head_img: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/photo-mr.jpg",
      shop_name: "",
      checkedSelect: false,
      theme_color: "",
      tipsShow: false,
      platform_protocol: false,
      register_protocol: false,
      popoverProtocolContent: {
        title: "",
        conten: ""
      },
      openAgreement: false
    };
  },

  activated() {},
  components: {},

  computed: {},

  mounted() {
    this.getData();
    if(this.fun.isDouYinApp()) {
      this.getDouYinSdkConfig();//获取抖音sdk配置
    }

    let basic_info = JSON.parse(localStorage.getItem("yz_basic_info"));
    if (basic_info?.home?.mailInfo?.default_head_img) {
      this.default_head_img = basic_info?.home?.mailInfo?.default_head_img;
    }
    window.firstLogin = 0;
  },

  methods: {
    tapShowAgreement(key) {
      if (key == "register") {
        this.openAgreement = true;
        this.popoverProtocolContent.title = this.register_protocol.title;
        this.popoverProtocolContent.content = this.register_protocol.content;
      } else {
        this.openAgreement = true;
        this.popoverProtocolContent.title = this.platform_protocol.title;
        this.popoverProtocolContent.content = this.platform_protocol.content;
      }
    },
    comfirm() {
      this.checkedSelect = true;
      this.beforeToLogin();
    },
    getData() {
      $http
        .post("privacy-policy.index", {}, "登录中")
        .then(res => {
          if (res.result == 1) {
            this.shop_name = res.data.shop_name;
            this.register_protocol = res.data.register_protocol;
            this.platform_protocol = res.data.platform_protocol;
            this.default_head_img = res.data.shop_logo;
            if (res.data.register_protocol && res.data.register_protocol.id && res.data.register_protocol.default_tick) {
              this.checkedSelect = res.data.register_protocol.default_tick;
            }
            if (res.data.theme_color) {
              let root = document.querySelector(":root");
              root.style.setProperty("--themeBaseColor", res.data.theme_color);
              root.style.setProperty("--themeLoadingColor", res.data.theme_color);
              this.theme_color = res.data.theme_color;
            }
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    async getDouYinSdkConfig() {
      // let href = this.fun.isIosOrAndroid() === "ios" ? window.initUrl : document.location.href;
      let href = this.$route.query.yz_redirect;
      let { result, msg, data } = await $http.get('plugin.douyin-set.frontend.index.getJsSdkConfig',{ url: href },".");
      if(result == 0) this.$toast(msg);
      this.douYinConfig = data;
      let { client_key, timestamp, nonce_str, signature } = data;
      const url = base64_decode(href);
      console.log('链接=============',url)
      sdk.config({
        params: {
          client_key: client_key, // clientKey在你的网页应用申请通过后得到
          signature: signature, // 服务端计算的签名，该签名被抖音开放平台验证通过后方可调用jsb方法
          timestamp: timestamp,// 时间戳
          nonce_str: nonce_str,
          url: url // 为应用申请的 JSB 安全域名下的链接，需要携带协议。e.g. https://jsb.security.domain/page.html
        },
      });
      sdk.ready(() => {
        console.log('Config Ready回调=================')
      });
      sdk.error(res => {
        console.log(`SDK Config Error：：：：: ${JSON.stringify(res)}`);
      });
    },
    beforeToLogin(){
      if(this.fun.isDouYinApp()) {
        sdk.showOpenAuth({
          params: {
            client_key:this.douYinConfig.client_key,
            state: '',
            scopes: {
              user_info: 0, // 0: 必选；1: 可选，默认不选中； 2: 可选，默认选中
            },
            response_type: 'code'
          },
          success: (res) => {
            // ticket： Oauth 凭据，详见下方说明
            // grant_permissions： String 类型，用户授权的所有 scope，以“,”拼接，例：user_info,mobile
            let { ticket, grant_permissions } = res;
            console.log(`Auth Success:=========== ${ticket},${grant_permissions},${JSON.stringify(res)}`);
            this.toLogin({'ticket': ticket});
          },
          error: res => {
            console.log(`Auth Error:::::: ${JSON.stringify(res)}`);
          }
        });
      } else {
        this.toLogin({});
      }
    },
    toLogin({ticket = ''}) {
      if (this.register_protocol || this.platform_protocol) {
        if (!this.checkedSelect) {
          this.tipsShow = true;
          return;
        }
      }
      let yz_redirect = this.$route.query.yz_redirect;
      let json = { yz_redirect: yz_redirect || "" };
      if (this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
        // 判断是否从企业微信侧边栏进入
        json.crop_id = this.fun.getKey("crop_id");
        json.client = "work";
      }
      if(ticket) {
        json.ticket = ticket;
      }
      if (window.isMiniprogram) {
        // 小程序 web-view 环境
        json.webview = "1";
      }
      window.history.replaceState(null, "", base64_decode(yz_redirect));
      let url = this.fun.getSiteRoot() + this.fun.getRealUrl("member.login.index", json);
      let URL = this.fun.deeplinkURL(url); //添加随机数，防止部分机型微信环境下跳转后页面没有刷新
      try {
        window.location.href = URL;
      } catch (error) {
        console.log(error);
      }
    },
    toMember() {
      window.firstLogin = 0;
      this.$router.replace(this.fun.getUrl("member"));
    }
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
#AuthorizedLogin {
  min-height: 100vh;
  background: #fff;
  .speace {
    height: 1rem;
    width: 100%;
  }
  .txt {
    font-size: 0.94rem;
    font-weight: bold;
    text-align: left;
    margin: 0.81rem 0.94rem 0 0.94rem;
  }

  .btnBox {
    display: flex;
    flex-direction: column;
    margin: 0 1.81rem;
    .van-button {
      height: 2.75rem !important;
    }
    .agreement {
      font-size: 0.81rem;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      margin-top: 1.88rem;
      .van-checkbox {
        flex-shrink: 0;
      }
      .agreement_txt {
        margin-left: 0.38rem;
        text-align: left;
        line-height: 1.2rem;
      }
      .redTxt {
        color: var(--themeLoadingColor);
      }
    }
  }
  .shopBox {
    margin: 0 0.94rem;
    padding: 0.94rem 0 1.25rem 0;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    border-bottom: 1px solid #f0f0f1;
    .img {
      width: 2.5rem;
      height: 2.5rem;
      border-radius: 50%;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
    .shopName {
      margin-left: 0.44rem;
      font-size: 1.19rem;
      font-weight: bold;
    }
  }

  .contenBox {
    width: 15.63rem;
    border-radius: 0.63rem;
    background: #fff;
    .contenTitle {
      padding: 1.06rem 0 0.88rem 0;
      border-bottom: 1px solid #ececec;
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 0.88rem;
      .title {
        color: #6e6e79;
        margin-bottom: 0.325rem;
      }
      .agree {
        color: var(--themeLoadingColor);
      }
    }
  }

  .buttonBox {
    height: 2.78rem;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 0.94rem;
    line-height: 2.78rem;
    .btn_c {
      color: #6e6e79;
      flex: 1;
      border-right: 1px solid #ececec;
    }
    .btn {
      flex: 1;
      color: var(--themeLoadingColor);
    }
  }
}
.city-info {
  border-radius: 0.656rem;
  width: 20rem;
  height: 32rem;
  margin: 0 auto;
  // padding-bottom: 5rem;
  background: #fff;

  header {
    border-radius: 0.656rem 0.656rem 0 0;
  }

  #a_content {
    // width: 14.438rem;
    margin: 0.5rem 0.9rem;
    height: 24rem;
    overflow-y: scroll;

    ::v-deep img {
      max-width: 100%;
      display: flex;
    }
  }
  .openBtn {
    width: 12.75rem;
    height: 2.313rem;
    background-color: #f04d4d;
    border-radius: 0.188rem;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 1.193rem;
    margin: 0 auto;
    margin-top: 1.5rem;
    margin-bottom: 1.063rem;
  }
}
</style>
